/**
 * @author   zhangyp
 * @created  2013-8-19 下午5:07:09
 * @email    zviolet@163.com
 * TODO      对设备中已安装程序包的访问
 */
package com.bible.fire.util;

import java.io.File;
import java.util.List;

import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.util.Log;

import com.bible.fire.api.wps.WPSAssistant;
import com.bible.fire.local.AppContext;
import com.bible.fire.util.file.DownloadAsynTask;

public class PackageUtil {
	
	private static String TAG = PackageUtil.class.getSimpleName();
    	
	//查看某个程序是否安装
	public static boolean isInstall(String packageName ){
		PackageManager pm = AppContext.getContext().getPackageManager();
		//获得设备中所有的安装程序
		List<PackageInfo> list = pm.getInstalledPackages( 0 );
		if( list != null && list.size() > 0 ){
			for(PackageInfo info : list){
				if( info.packageName.equals( packageName ) ){
					return true;
				}
			}
		}
		return false;
	}
	
	public static void invokeAppToOpenFile(Context context, File file, boolean isSendSaveBroad, boolean isReadOnly ){
		int index = file.getName().lastIndexOf(".");
		if( index > 0 ){
			String fileType = file.getName().substring( index + 1 );
			if( WPSAssistant.isWpsSupportFileType(fileType) ){
				if( isReadOnly ){
					WPSAssistant.readFile(context, file);
				}else{
					WPSAssistant.openFile(context, file, isSendSaveBroad);
				}
			}else{
				openFileByThirdApp(context, file);
			}
		}else{
			openFileByThirdApp(context, file);
		}
	}
	
	public static void openFileByThirdApp(Context context, File file, Intent intent ){
		try{
			boolean isThridAppExist = false;
			if( intent != null ){
				ComponentName component = intent.getComponent();
				if( component != null ){
					String packageName = component.getPackageName();
					Log.d(TAG, "third package name = " + packageName );
					if( packageName != null && isInstall(packageName) ){
						isThridAppExist = true;
						context.startActivity(intent);
					}
				}				
			}
			if( !isThridAppExist ){
				openFileByThirdApp( context, file );
			}	
		}catch( ActivityNotFoundException e) {
			ToastUtil.showMsg(context, "没有找到相应的程序来打开此类型文件,请先安装对应的程序!");
		}
		
	}
	
	//调用其他程序打开文件
	public static void openFileByThirdApp(Context context, File file){
		try{
			if( file != null && context != null ){
				Intent intent = new Intent();
				intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
			    //执行动作     
			    intent.setAction(Intent.ACTION_VIEW);
			    //类别
			    //intent.addCategory(Intent.CATEGORY_DEFAULT);
			    //执行的数据类型  
			    //intent.setDataAndType(Uri.fromFile(file), "application/vnd.openxmlformats-officedocument.wordprocessingml.document");			    
			    intent.setDataAndType(Uri.fromFile(file), MIMETypeUtil.getMIMEType(file) );
			    context.startActivity(intent);
			}
		}catch( ActivityNotFoundException e) {
			ToastUtil.showMsg(context, "没有找到相应的程序来打开此类型文件,请先安装对应的程序!");
		}
		
	}
	
	//调用指定程序打开文件
	public static void openFileByDesignatedApp(Context context, File file, String packageName, String activityName ){
		try{
			if( file != null && context != null ){
				if( packageName != null && isInstall(packageName) ){
					Intent intent = new Intent(); 
					intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
				    //执行动作     
				    intent.setAction(Intent.ACTION_VIEW);
				    //类别
				    //intent.addCategory(Intent.CATEGORY_DEFAULT);
				    intent.setClassName(packageName, activityName );
				    //执行的数据类型     
				    intent.setData( Uri.fromFile(file) );
				    context.startActivity(intent);
				}else{
					openFileByThirdApp( context, file );
				}
			}
		}catch( ActivityNotFoundException e) {
			ToastUtil.showMsg(context, "没有找到相应的程序来打开此类型文件,请先安装对应的程序!");
		}		
	}
	
	//下载文件并安装
		public static void downloadFileAndInstall(String httpUrl, String savePath, Context context, boolean tip){
			if( httpUrl == null || savePath == null || context == null ){
				Log.e(TAG, "invalid download params");
				return;
			}
			ProgressDialog pd = new ProgressDialog( context );
			final String filePath = savePath;
			final Context fcontext = context;
			final Runnable runable = new Runnable(){
				@Override
				public void run() {				
					Intent intent = new Intent();    
				    //执行动作     
				    intent.setAction(Intent.ACTION_VIEW);    
				    //执行的数据类型     
				    intent.setDataAndType(Uri.fromFile( new File(filePath)), "application/vnd.android.package-archive");
				    fcontext.startActivity(intent);
				}			
			};
			if( tip ){
				final ProgressDialog fpd = pd;
				final String serverPath = httpUrl;
				WindowUtil.showOperateDialog( context , "确认下载文件并安装?", "提示", new Runnable(){
					public void run(){
						DownloadAsynTask.downloadSingleFile( serverPath, filePath, fpd, runable );
					}
				});
			}else{
				DownloadAsynTask.downloadSingleFile( httpUrl, savePath, pd, runable );
			}
		}
	
}
